package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.firefighting.MainActivity;
import com.dlwx.firefighting.R;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.ActivityCollector;
import com.dlwx.firefighting.utils.CheckUtil;
import com.dlwx.firefighting.utils.DealResult;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.LogUtils;
import com.dlwx.firefighting.utils.MD5Util;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.utils.VoidRepeatClickUtil;
import com.dlwx.firefighting.widget.CircleImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_back)
    ImageView img_back;
    @BindView(R.id.login_toregister)
    TextView to_register;
    @BindView(R.id.login_userheader_img)
    CircleImageView img_header;
    @BindView(R.id.login_edit_phone)
    EditText edit_phone;
    @BindView(R.id.login_edit_psw)
    EditText edit_psw;
    @BindView(R.id.button_login)
    TextView btn_login;
    @BindView(R.id.login_by_wechat)
    ImageView img_wechat;
    @BindView(R.id.login_by_qq)
    ImageView img_qq;

    String str_phone;
    String str_psw;
    @BindView(R.id.img_remember)
    ImageView imgRemember;
    @BindView(R.id.middle_view)
    View middleView;
    @BindView(R.id.tv_find_psw)
    TextView tvFindPsw;
    @BindView(R.id.img_eye)
    ImageView imgEye;
    private boolean isRemeber = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        //设置状态栏
        // MyStatusBar.setStatusBar(LoginActivity.this, ContextCompat.getColor(this, R.color.white), 0);
        //编辑框触摸显示光标
        edit_phone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    edit_phone.setCursorVisible(true);
                }
                return false;
            }
        });
        edit_phone.addTextChangedListener(textWatcher);
        edit_psw.addTextChangedListener(textWatcher);
        imgEye.setBackgroundResource(R.mipmap.eye);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRemeber = (boolean) SPUtils.get(this, Constant.IS_REMEMBER, false);
        isMember = (boolean) SPUtils.get(this, Constant.IS_MEMBER, true);
    }

    private boolean isSee = false;
    private boolean isMember = true;

    @OnClick({R.id.login_back, R.id.login_toregister, R.id.button_login, R.id.login_by_wechat
            , R.id.login_by_qq, R.id.img_remember, R.id.tv_find_psw, R.id.img_eye})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_back:         //退出
                //finish();
                ActivityCollector.getInstances().finishAllActivity();
                break;
            case R.id.login_toregister:   //注册
                if (!VoidRepeatClickUtil.isFastDoubleClick()) {
                    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                }
                break;
            case R.id.button_login:       //登陆
                if (checkUserInfo()) {
//                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        login();
                }
                break;
            case R.id.login_by_wechat:    //微信登录
                ToastUtils.toastForLong(this, "微信登陆");
                break;
            case R.id.login_by_qq:        //qq登录
                ToastUtils.toastForLong(this, "qq登陆");
                break;
            case R.id.tv_find_psw:        //忘记密码
                startActivity(new Intent(LoginActivity.this, FindPswActivity.class));
                break;
            case R.id.img_eye:        //
                if (isSee) {
                    edit_psw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isSee = false;
                    imgEye.setBackgroundResource(R.mipmap.eye);
                } else {
                    edit_psw.setInputType(InputType.TYPE_CLASS_TEXT);
                    isSee = true;
                    imgEye.setBackgroundResource(R.mipmap.eye_open);
                }
                break;
        }
    }

//收银员登录
    private void loginByCashier() {
        DialogUtils.showProgressDlg(this, "");
        OkGo.<String>get(Constant.LOGIN_CASHIER)
//                .tag(this)
//                .params("user", str_phone)
//                .params("pwd", str_psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        String res = response.body().toString();
                            ToastUtils.toastForLong(LoginActivity.this,res);
//                        BaseBean<UserBean> bean = new Gson().fromJson(res, new TypeToken<BaseBean<UserBean>>() {
//                        }.getType());
//                        if (Constant.SUCESS == bean.getStatus()) {
//
//                            SPUtils.put(LoginActivity.this, Constant.USER_ID, bean.getData().get(0).getUser_id());
//                            if (isRemeber) {
//                                SPUtils.put(LoginActivity.this, Constant.isLogin, true);
//                                SPUtils.put(LoginActivity.this, Constant.LOGIN_NAME, bean.getData().get(0).getUser_name());
//                                SPUtils.put(LoginActivity.this, Constant.LOGIN_PSW, str_psw);
//                            }
//                            //设置推送别名
//                            JPushInterface.setAlias(LoginActivity.this, Constant.SUCESS, bean.getData().get(0).getUser_id());
//                            LogUtils.d("...........>"+bean.getData().get(0).getUser_id());
//                            SPUtils.put(LoginActivity.this, Constant.CASH_MONEY, bean.getData().get(0).getUser_money());
//                            SPUtils.put(LoginActivity.this, Constant.IS_MEMBER, false);
//                            SPUtils.put(LoginActivity.this, Constant.userName, bean.getData().get(0).getUser_name());
//                            SPUtils.put(LoginActivity.this, Constant.userPhone, bean.getData().get(0).getMobile_phone());
//                            startActivity(new Intent(LoginActivity.this, MainCashierActivity.class));
//                            LoginActivity.this.finish();
//                        } else {
//                            ToastUtils.toastForLong(LoginActivity.this, bean.getMsg());
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        super.onError(response);
                        ToastUtils.toastForShort(LoginActivity.this, getString(R.string.bad_net));
                    }
                });
    }

    private void login() {
        DialogUtils.showProgressDlg(this, "");
        str_psw=MD5Util.getMD5(str_psw);
        LogUtils.i(str_psw);
        OkGo.<String>post(Constant.LOGIN)
                .tag(this)
                .params("username", str_phone)
                .params("password", str_psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        int code =  DealResult.getInstance().deal(LoginActivity.this, response);
                        if(code==Constant.SUCESS){
                            SPUtils.put(LoginActivity.this, Constant.isLogin, true);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            LoginActivity.this.finish();
                            loginByCashier();
                        }
//                        String res = response.body().toString();
//                        BaseBean<UserBean> bean = new Gson().fromJson(res, new TypeToken<BaseBean<UserBean>>() {
//                        }.getType());
//
//                        if (Constant.SUCESS == bean.getStatus()) {
//                            LogUtils.d("...........>");
//                            SPUtils.put(LoginActivity.this, Constant.USER_ID, bean.getData().get(0).getUser_id());
//                            if (isRemeber) {
//                                SPUtils.put(LoginActivity.this, Constant.isLogin, true);
//                                SPUtils.put(LoginActivity.this, Constant.LOGIN_NAME, bean.getData().get(0).getUser_name());
//                                SPUtils.put(LoginActivity.this, Constant.LOGIN_PSW, str_psw);
//                            }
//                            String transferStatus=bean.getData().get(0).getTransfer_accounts_status().trim();
//                            if(TextUtils.equals("1",transferStatus)){
//                                SPUtils.put(LoginActivity.this, Constant.IS_SCAN, true);
//                            }else{
//                                SPUtils.put(LoginActivity.this, Constant.IS_SCAN, false);
//                            }
//                            SPUtils.put(LoginActivity.this, Constant.IS_MEMBER, true);
//                            SPUtils.put(LoginActivity.this, Constant.userName, bean.getData().get(0).getUser_name());
//                            SPUtils.put(LoginActivity.this, Constant.userPhone, bean.getData().get(0).getMobile_phone());
//                            SPUtils.put(LoginActivity.this, Constant.userBlankCard, bean.getData().get(0).getBank_card_number());
//                            SPUtils.put(LoginActivity.this, Constant.PAY_PASSWORD, bean.getData().get(0).getPay_password());
//                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
////                            startActivity(new Intent(LoginActivity.this, TimeService.class));
//                            giveMoney(1);
//                            LoginActivity.this.finish();
//                        } else {
//                            ToastUtils.toastForLong(LoginActivity.this, bean.getMsg());
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        super.onError(response);
                        ToastUtils.toastForShort(LoginActivity.this, getString(R.string.bad_net));
                    }
                });
       /* KeyBoardUtils.closeKeybord(LoginActivity.this);*/
    }

    /**
     * 检查用户名和密码格式
     */
    private boolean checkUserInfo() {
        str_phone = edit_phone.getText().toString();
        str_psw = edit_psw.getText().toString();
        if (TextUtils.isEmpty(str_phone)) {
            edit_phone.setText("");
            ToastUtils.toastForLong(LoginActivity.this, "用户名不能为空！");
            return false;
        }
        if (!CheckUtil.checkPassword(str_psw) || str_psw.length() < 6) {
            edit_psw.setText("");
            ToastUtils.toastForLong(LoginActivity.this, "密码格式错误");
            return false;
        }
        return true;
    }

    /**
     * 当手机号码长度为11，密码长度大于5时，登陆按钮变亮
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // if (edit_phone.getText().toString().length() == 11 && edit_psw.getText().toString().length() > 5) {
//            if (edit_psw.getText().toString().length() > 5) {
//                btn_login.setBackgroundResource(R.drawable.bg_green_selector);
//            } else {
//                btn_login.setBackgroundResource(R.drawable.bg_grey);
//            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    /**
     * 从注册界面点击返回按钮直接退出APP
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityCollector.getInstances().finishAllActivity();
    }

    //根据在线时长赠送余额
    private void giveMoney(final int type) {
        String userId= (String) SPUtils.get(getApplicationContext(),Constant.USER_ID,"");
        OkGo.<String>post(Constant.ONLINE)
                .params("user_id", userId)
                .params("online_time", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(type==60){
                            SPUtils.put(getApplicationContext(), Constant.IS_COUNT_TIME,false);
                        }
//                        SPUtils.put(getApplicationContext(), Constant.IS_COUNT_TIME,false);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(getApplicationContext(), getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    //------------------------------------------------------------------
}
